#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
主题:查找最大或最小的 N 个元素
问题: 怎样从一个集合中获得最大或者最小的 N 个元素列表？
提示 : 
    1. 堆数据结构最重要的特征是 heap[0] 永远是最小的元素
"""

import heapq


def main():
    print('recipe1'.center(20,'*'))
    recipe1()
    print('recipe2'.center(20,'*'))
    recipe2()
    print('recipe3'.center(20,'*'))
    recipe3()


def recipe1():
    '''heapq 模块解决这个问题'''
    nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]
    print(f"{nums = }")
    print(f"{heapq.nlargest(3, nums) = }")
    print(f"{heapq.nsmallest(3, nums) = }")


def recipe2():
    '''更复杂的数据结构'''
    portfolio = [
        {'name': 'IBM', 'shares': 100, 'price': 91.1},
        {'name': 'AAPL', 'shares': 50, 'price': 543.22},
        {'name': 'FB', 'shares': 200, 'price': 21.09},
        {'name': 'HPQ', 'shares': 35, 'price': 31.75},
        {'name': 'YHOO', 'shares': 45, 'price': 16.35},
        {'name': 'ACME', 'shares': 75, 'price': 115.65}
    ]
    print(f"{portfolio = }")
    cheap = heapq.nsmallest(3, portfolio, key=lambda s: s['price'])
    expensive = heapq.nlargest(3, portfolio, key=lambda s: s['price'])
    print(f"{cheap = }")
    print(f"{expensive = }")


def recipe3():
    '''在底层实现里面，首先会先将集合数据进行堆排序后放入一个列表中'''
    nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]
    print(f"{nums = }")
    heap = list(nums)
    heapq.heapify(heap)
    print(f"{heap = }")
    # 最小的3个元素
    print(f"{heapq.heappop(heap) = }")
    print(f"{heapq.heappop(heap) = }")
    print(f"{heapq.heappop(heap) = }")


if __name__ == '__main__':
    main()
